<template>
  <view class="content">
    <RainbowProgressBar :progress="currentProgress" :max-value="maxValue" />
    <sp-html2pdf-render
        domId="render-dom"
        ref="renderRef"
        pdfFileName="这是一个pdf文件"
        @beforeSavePDF="beforeSavePDF"
        @successSavePDF="successSavePDF"
        @renderOver="renderOver"
    ></sp-html2pdf-render>

    <!-- 主渲染内容 -->
    <view id="render-dom" class="render-content">
      <h4>有问题欢迎进群讨论，QQ交流群: 852637893</h4>
      <view style="width:750rpx; height:750rpx">
        <l-echart ref="chartRef" @finished="init"></l-echart>
      </view>
      <div>
        <image :src="src" mode="widthFix"></image>
      </div>
    </view>
    <!-- 导出按钮自定义 -->
    <button @click="cusRenderDom">导出</button>


    <button @click="btn1">读取图片</button>
    <image class="logo" :src="newImg"></image>
    <view class="text-area">
      <text class="title">{{ title }}</text>
      <button @click="btn">测试</button>
      <fui-autograph id="myCanvas" width="300" height="300" ref="autograph" @ready="ready"></fui-autograph>

      <button @click="complete">保存</button>
      <button @click="del">删除</button>
      <button @click="change">修改</button>
      <div>
        <image :src="src" mode="widthFix"></image>
      </div>


    </view>
  </view>
</template>

<script>
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
import {deleteById, readJsonFromFile, updateJsonById, writeJsonToFile} from "@/utils/fileUtil";
import FuiAutograph from "@/components/firstui/fui-autograph/fui-autograph.vue";
import SpHtml2pdfRender from "@/uni_modules/sp-html2pdf-render/components/sp-html2pdf-render/sp-html2pdf-render.vue";
import {getAbsolutePath} from "@/utils";
import RainbowProgressBar from "@/components/RainbowProgressBar/RainbowProgressBar.vue";

export default {
  components: {RainbowProgressBar, SpHtml2pdfRender, FuiAutograph},
  data() {
    return {
      currentProgress: 50, // 初始进度
      maxValue: 900, // 默认最大值
      option: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          confine: true
        },
        legend: {
          data: ['热度', '正面', '负面']
        },
        grid: {
          left: 20,
          right: 20,
          bottom: 15,
          top: 40,
          containLabel: true
        },
        xAxis: [
          {
            type: 'value',
            axisLine: {
              lineStyle: {
                color: '#999999'
              }
            },
            axisLabel: {
              color: '#666666'
            }
          }
        ],
        yAxis: [
          {
            type: 'category',
            axisTick: {show: false},
            data: ['汽车之家', '今日头条', '百度贴吧', '一点资讯', '微信', '微博', '知乎'],
            axisLine: {
              lineStyle: {
                color: '#999999'
              }
            },
            axisLabel: {
              color: '#666666'
            }
          }
        ],
        series: [
          {
            name: '热度',
            type: 'bar',
            label: {
              normal: {
                show: true,
                position: 'inside'
              }
            },
            data: [300, 270, 340, 344, 300, 320, 310],
          },
          {
            name: '正面',
            type: 'bar',
            stack: '总量',
            label: {
              normal: {
                show: true
              }
            },
            data: [120, 102, 141, 174, 190, 250, 220]
          },
          {
            name: '负面',
            type: 'bar',
            stack: '总量',
            label: {
              normal: {
                show: true,
                position: 'left'
              }
            },
            data: [-20, -32, -21, -34, -90, -130, -110]
          }
        ]
      },


      title: 'Hello',
      canvasId: '',
      src: '',
      newImg: ""
    }
  },
  onLoad() {
    setTimeout(() =>{
      this.currentProgress = 600
    },2000)
  },
  methods: {
    async init() {
      // chart 图表实例不能存在data里
      const chart = await this.$refs.chartRef.init(echarts);
      chart.setOption(this.option)
    },

    cusRenderDom() {
      // 调用组件实例中h2pRenderDom方法
      this.$refs.renderRef.h2pRenderDom();
    },
    renderOver(e) {
      // e为导出的图片（base64）
      console.log("==== renderOver :", e);

    },
    beforeSavePDF(e) {
      // e为导出的pdf（base64）
      // console.log("==== beforeSavePDF :", e);
    },
    successSavePDF(path) {
      const printPdf = uni.requireNativePlugin('YanYu-PrintPDF');
      // e为打开的pdf（临时路径）
      console.log("==== successSavePDF :", path);
      getAbsolutePath(path).then(absolutePath => {
        console.log('文件的绝对路径:', absolutePath);
        printPdf.managerPrint(absolutePath);
      }).catch(error => {
        console.error('获取绝对路径失败:', error);
      });
      // uni.saveFile({
      //   tempFilePath:path, //临时路径
      //   success: (res) => {
      //     console.log("保存成功",res.savedFilePath)
      //     console.log("打印中",printPdf)
      //     printPdf.managerPrint(res.savedFilePath);
      //
      //   },
      // })
    },


    async btn() {
      let obj = {
        name: 'zhangsan',
      }
      let arr = []
      arr.push(obj)
      console.log("123123")
      await writeJsonToFile(arr, '/sdcard/test/user.json')

      let res = readJsonFromFile('/sdcard/test/user.json')
      console.log(res)
      for (let i = 0; i < res.length; i++) {
        console.log(res[i].name)
      }

    },

    // 删除
    del(){
      let res = readJsonFromFile('/sdcard/test/user.json')
      console.log(res)
      deleteById('17389852748866079', '/sdcard/test/user.json')

      let res2 = readJsonFromFile('/sdcard/test/user.json')
      console.log(res2)
    },

    // 修改
    change(){
      const success = updateJsonById(
          "17389913691558562",
          {
            name: "新的名称",
            sex:"男"
          },
          "/sdcard/test/user.json"
      );
      console.log("修改成功", success)
      let res2 = readJsonFromFile('/sdcard/test/user.json')
      console.log(res2)
    },

    ready(e) {
      this.canvasId = e.canvasId
    },
    //重新签名
    redraw() {
      if (!this.canvasId) return;
      this.src = '';
      this.$refs.autograph.redraw()
    },
    //完成签名
    complete() {
      if (!this.canvasId || this.src) return;
      this.$refs.autograph.drawComplete((res) => {
        //res为签名图片
        this.src = res;
        console.log("当前的图片",this.src)
        uni.saveFile({
          tempFilePath: res, // 需要保存的文件的临时路径
          success: function(res) {
            var savedFilePath = res.savedFilePath; // 文件的保存路径 (持久化的)
            console.log('文件已保存至:', savedFilePath);
            // 在这里可以对 savedFilePath 进行进一步处理，比如上传服务器或记录到数据库等
            let obj = {
              url: ""
            }
            obj.url = savedFilePath
            writeJsonToFile(obj, '/sdcard/test/img.json')

            let res2 = readJsonFromFile('/sdcard/test/img.json')
            console.log(res2)
          },
          fail: function(err) {
            console.error('文件保存失败:', err);
          }
        });
      })

    },

    btn1() {
      let res = readJsonFromFile('/sdcard/test/img.json')
      console.log(res)
      for (let i = 0; i < res.length; i++) {
        console.log(res[i].url)
        this.newImg = res[i].url
      }
    }
  },


}
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin: 200rpx auto 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}
</style>
